package com.dkha.server.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkha.common.enums.*;
import com.dkha.common.fileupload.MinioUtil;
import com.dkha.common.http.HttpUtil;
import com.dkha.common.modules.vo.ReturnVO;
import com.dkha.common.modules.vo.control.ControlTaskVedioVO;
import com.dkha.common.modules.vo.control.TaskControlVO;
import com.dkha.common.modules.vo.control.VideoControlVo;
import com.dkha.common.modules.vo.face.ControlTaskVO;
import com.dkha.common.page.PageParam;
import com.dkha.common.result.CommonResult;
import com.dkha.common.systemcode.SystemCode;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.mappers.ControlLibraryMidMapper;
import com.dkha.server.mappers.ControlTaskMapper;
import com.dkha.server.mappers.FaceCameraDao;
import com.dkha.server.mappers.FaceLibraryMapper;
import com.dkha.server.modules.entities.*;
import com.dkha.server.services.*;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;
import java.util.regex.Pattern;

/**
 * <p>
 * 布控任务 服务实现类
 * </p>
 *
 * @author Spring
 * @since 2019-12-09
 */
@Service
@Slf4j
public class ControlTaskServiceImpl extends ServiceImpl<ControlTaskMapper, ControlTask> implements IControlTaskService {

    @Autowired
    ControlTaskMapper controlTaskMapper;
    @Autowired
    FaceLibraryMapper faceLibraryMapper;
    @Autowired
    FaceCameraDao faceCameraDao;
    @Autowired
    ControlBayonetMidServiceImpl controlBayonetMidService;
    @Autowired
    ControlLibraryMidMapper controlLibraryMidMapper;
    @Autowired
    ControlLibraryMidServiceImpl controlLibraryMidService;
    @Autowired
    FaceCameraServiceImpl faceCameraServiceImpl;
    @Autowired
    private IPortraitService iPortraitService;

    @Autowired
    private IFaceLibraryService iFaceLibraryService;
    @Autowired
    private FaceCameraService faceCameraService;

    @Value("${api.server.prefix}")
    private String link;
    @Value("${videotype}")
    private String videoreg = "(mp4|flv|avi|rm|rmvb|wmv)";

    @Resource
    private HttpUtil httpUtil;

    @Autowired
    private MinioUtil minioUtil;

    @Override
    public Page<ControlTask> getList(PageParam pageParam,Integer videotype) {
        if (pageParam.getPageNo() < 1) {
            pageParam.setPageNo(1);
        }
        if (pageParam.getPageSize() < 0 || pageParam.getPageSize() > 500) {
            pageParam.setPageSize(20);
        }
        Page<ControlTask> page = new Page<>(pageParam.getPageNo(), pageParam.getPageSize());
        //分页查询
        List<ControlTask> facetaskLists=null;
        if(videotype==-1) {
            facetaskLists = controlTaskMapper.getviedoTaskList(page, pageParam.getNote());
        }else
        {
            facetaskLists = controlTaskMapper.getTaskList(page, pageParam.getNote());
        }
        for (ControlTask ct : facetaskLists) {
            //生成摄像头列表的区域信息
            ct.setTasklibstr( this.getLibRegionBytaskid(ct.getIdControlTask().toString()));
            //摄像头名称
            List<FaceCameraEntity> faceCameras = controlBayonetMidService.selectFaceCameraBytaskID(ct.getIdControlTask().toString());
            ct.setListfacecamera(faceCameras);
            //视频任务列表，需要获取任务状态
            if(-1==videotype){
                try {
                    ct.setTaskstatus(TaskStatuEnum.STATUS_WORKING.getMessage());
                    Map<String, Object> resultMap = (Map<String, Object>) httpUtil.get(link + ApiUrlEnum.ALARMS_STATUS.getUrl() + "/" + ct.getTaskNo(), Map.class);
                    if (resultMap != null) {
                        if (ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString())) {
                            Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
                            if (data != null && data.get("status") != null) {
                                if (TaskStatuEnum.STATUS_OVER.getCode().equalsIgnoreCase(data.get("status").toString())) {
                                    ct.setTaskstatus(TaskStatuEnum.STATUS_OVER.getMessage());
                                }
                            }
                        }
                    }

                }catch (Exception ex){
                }
            }
        }
        page.setRecords(facetaskLists);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addControlTask(TaskControlVO taskvo) {

        List<String> listcamera = taskvo.getListcamera();
        if(listcamera==null||listcamera.size()==0) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "布控摄像头信息不能为空！");
        }
        try {
            /*1 校验区域所属的摄像头是否有任务执行 */
            //保存摄像头列表
            List<ControlBayonetMid> listBayone = new ArrayList<>();
            List<FaceCameraEntity> listBayonebyUse = new ArrayList<>();
            List<String> camerList = new ArrayList<>();
            //存储摄像头的区域码表
            HashMap<String,Integer> cameraRegion=new HashMap<>();
            for (String camerid : listcamera) {
                ControlBayonetMid controlBayonetMid = new ControlBayonetMid();
                FaceCameraEntity faceCamera = faceCameraService.getById(camerid);
//                System.out.println("输出摄像头状态");
//                System.out.println(faceCamera.getStatus());
//                System.out.println("输出摄像头地址");
//                System.out.println(faceCamera.getRtspUrl());

                if (faceCamera.getStatus().equals(YNEnums.NO.code)){
                    faceCameraServiceImpl.status(faceCamera.getIdFaceCamera(),true);
                }
                System.out.println(faceCamera.getStatus());
                if (controlBayonetMidService.selectexistByCarmeID(camerid) == 0) {
                    //依次判断摄像头是否添加到任务中
                    controlBayonetMid.setIsValid(YNEnums.YES.code);
                    controlBayonetMid.setIdFaceCamera(faceCamera.getIdFaceCamera());
                    camerList.add(faceCamera.getIdFaceCamera().toString());
                    listBayone.add(controlBayonetMid);
                    cameraRegion.put(faceCamera.getCameraRegionFirstlevel(),1);
                } else {
                    listBayonebyUse.add(faceCamera);
                }
            }
            if (!UtilValidate.isEmpty(listBayonebyUse)) {
                return new CommonResult(listBayonebyUse, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "该区域下摄像头有被其他任务使用！");
            }
            //保存库列表
            List<ControlLibraryMid> listbibray = new ArrayList<>();
            List<String> listbibraybyUse = new ArrayList<>();
            List<String> listlibs = taskvo.getLibIds();
            for (String libid : listlibs) {
                if (controlLibraryMidMapper.selectexistByLibID(libid, YNEnums.YES.code) > 0) {
                    ControlLibraryMid clm = new ControlLibraryMid();
                    clm.setIdFactory(Long.parseLong(libid.toString()));
                    clm.setIsValid(YNEnums.YES.code);
                    listbibray.add(clm);
                } else {
                    listbibraybyUse.add(libid);
                }
            }
            if (!UtilValidate.isEmpty(listbibraybyUse)) {
                return new CommonResult(listbibraybyUse, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "该任务存在无效库！");
            }
            // 调用平台API接口
            ControlTaskVO ctvo = new ControlTaskVO();
            //任务名称
            String strTaskNo = "00000000";
            ctvo.setName(taskvo.getTaskName());
            ctvo.setThreshold(taskvo.getControlThreshold());
            ctvo.setCameraId(camerList);
            ctvo.setLibraryId(taskvo.getLibIds());
            List<String> listcamera1 = taskvo.getListcamera();
            String s = listcamera1.get(0);
            System.out.println("当前添加的摄像头id");
            System.out.println(s);
            FaceCameraEntity faceCameraEntity = faceCameraService.getById(s);
            String rtspUrl = faceCameraEntity.getRtspUrl();
            System.out.println(rtspUrl);

//            System.out.println("设置编码为：9249924");
//            Map<String,Object> resultMap = ( Map<String,Object>) httpUtil.post(link+ApiUrlEnum.TASK_POSTURL.getUrl(), ctvo,  Map.class);
//            if(resultMap!=null){
//                if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString()))
//                {
//                    Map<String,Object> data=  (Map<String,Object>) resultMap.get("data");
//                    if(data!=null&&data.get("taskId")!=null){
//                        strTaskNo=data.get("taskId").toString();
//                    }else
//                    {
//                        return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！没有获取到任务编号");
//                    }
//                }else {
//                    return new CommonResult(resultMap, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！");
//                }
//            }else {
//                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！");
//            }
//            strTaskNo="9249924";
            //后端处理taskID
            Long testNo = System.currentTimeMillis();
            String testNostring = testNo.toString();
            System.out.println("设置编码为"+testNostring);
            strTaskNo = testNostring;
            System.out.println("开始添加任务");
            String testUrl = "http://192.168.1.196:5001/addTask/";
            System.out.println(strTaskNo);
            //获取布控的库id和名称
            String libId =taskvo.getLibIds().get(0);
            String libName = faceLibraryMapper.selectById(libId).getFactoryName();
            ReturnVO returnVO = (ReturnVO)httpUtil.get(testUrl+"?strtaskno="+strTaskNo+"&rtspurl="+rtspUrl+"&libId="+libId+"libName"+libName,null, ReturnVO.class);
            System.out.println("输出新建结果");
            System.out.println(returnVO);
            if(returnVO.getCode().equals(ErrEnum.OK.getCode())){
                System.out.println("任务远程保存成功");
                ControlTask controlTask = new ControlTask();
                controlTask.setTaskNo(strTaskNo);
                System.out.println("再次输出");
                System.out.println(strTaskNo);
                BeanUtils.copyProperties(taskvo, controlTask);
                //设置任务区域
                controlTask.setControlRegion(this.getCameraRegionStringByCameraList(cameraRegion));
                controlTask.setIsValid(TaskStatusEnum.RUN.code);
                //保存任务
                if (this.save(controlTask)) {
                    for (ControlBayonetMid cbm : listBayone) {
                        //设置任务编号
                        cbm.setIdControlTask(controlTask.getIdControlTask());
                    }
                    for (ControlLibraryMid clm : listbibray) {
                        //设置任务编号
                        clm.setIdControlTask(controlTask.getIdControlTask());
                    }
                    //批量 保存摄像头列表
                    controlBayonetMidService.saveBatch(listBayone);
                    //批量 保存库ID列表
                    controlLibraryMidService.saveBatch(listbibray);
                    return new CommonResult(controlTask.getTaskNo(), SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
                } else {
                    log.error("任务保存：{}", controlTask.getTaskNo());
                    return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "保存任务信息失败！");
                }
            }else {
                System.out.println("远程任务保存失败");
                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "保存任务信息失败！");
            }

        } catch (Exception ex) {
            log.error("保存任务异常：{}", ex.getMessage());
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "保存任务信息失败！"+ex.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateControlTask(TaskControlVO controlTask) {
        //根据任务ID查询任务信息
        ControlTask controlOne = this.getById(controlTask.getIdControlTask());
        if (controlOne == null) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "参数异常，非法的任务ID！查询不到有效任务");
        } else {
            try {
                controlOne.setTaskName(controlTask.getTaskName());
                controlOne.setDisposalType(controlTask.getDisposalType());
                controlOne.setRemarks(controlTask.getRemarks());
                controlOne.setControlThreshold(controlTask.getControlThreshold());
                this.updateById(controlOne);
            } catch (Exception ex) {
                log.error("修改任务异常：{}", ex.getMessage());
                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "修改任务信息失败！");
            }
        }
        return new CommonResult(controlOne, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deleteControlTask(String taskID) {
        //根据任务ID查询任务信息
        ControlTask controlOne = this.getById(taskID);
        if (controlOne == null) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "参数异常，非法的任务ID！");
        } else {
            try {
                boolean isDeleteApi = false;
                //1. 调用平台API接口
//                Map<String, Object> resultMap = (Map<String, Object>) httpUtil.delete(link + ApiUrlEnum.TASK_POSTURL.getUrl() + "/" + controlOne.getTaskNo(), Map.class);
//                if (resultMap != null) {
//                    if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString())){
//                        isDeleteApi=true;
//                    }
//                } else {
//                    return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API删除任务信息失败！");
//                }
                System.out.println("开始删除任务");
                String testUrl = "http://192.168.1.196:5001/delTask/";
                ReturnVO returnVO = (ReturnVO)httpUtil.get(testUrl+"?strtaskno="+controlOne.getTaskNo(),null, ReturnVO.class);
                System.out.println("输出删除结果");
                System.out.println(returnVO);
                if(returnVO.getCode().equals(ErrEnum.OK.getCode())){
                    System.out.println("任务远程删除成功");
                    isDeleteApi = true;
                }else {
                    System.out.println("远程任务删除失败");
                }
                if (isDeleteApi) {
                    List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskID(taskID);
                    for (FaceCameraEntity faceCameraEntity : listfaceCamera){
                        Long deleteID = faceCameraEntity.getIdFaceCamera();
                        if (faceCameraEntity.getStatus().equals(YNEnums.YES.code)){
                            faceCameraServiceImpl.status(deleteID,false);
                        }
                    }
                    // 删除任务摄像头中间管理库
                    controlBayonetMidService.deletetaskandcarmerbytaskid(taskID);
                    // 删除任务特征库中间管理库
                    controlLibraryMidService.deletetaskLibraryMidbytaskid(taskID);
                    // 删除本地数据库
                    this.removeById(taskID);
                } else {
                    return new CommonResult(taskID, SystemCode.DELETE_FAILED.code, "平台API删除任务信息失败");
                }
            } catch (Exception ex) {
                log.error("删除任务异常：{}", ex.getMessage());
                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "删除任务信息失败！");
            }
        }
        return new CommonResult(taskID, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
    }

    @Override
    public CommonResult getCameraListByTaskID(String taskID) {
        List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskID(taskID);
        if (listfaceCamera != null) {
            return new CommonResult(listfaceCamera, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
        } else {
            return new CommonResult(null, SystemCode.HANDLER_FAILED.code, SystemCode.HANDLER_FAILED.des);
        }
    }

    @Override
    public CommonResult getCameraListByTaskNO(String taskNO) {
        List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskNo(taskNO);
        if (listfaceCamera != null) {
            return new CommonResult(listfaceCamera, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
        } else {
            return new CommonResult(null, SystemCode.HANDLER_FAILED.code, SystemCode.HANDLER_FAILED.des);
        }
    }
    /**
     * 停止订单信息 调用底层删除任务，本地库修改为停止状态
     * @param taskID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult stopControlByTaskID(String taskID) {
        ControlTask controlOne = this.getById(taskID);
        if (controlOne == null) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "参数异常，非法的任务ID！");
        } else {
            boolean isDeleteApi = true;
            try{
                //1. 调用平台API接口
//                Map<String, Object> resultMap = (Map<String, Object>) httpUtil.delete(link + ApiUrlEnum.TASK_POSTURL.getUrl() + "/" + controlOne.getTaskNo(), Map.class);
//                if (resultMap != null) {
//                    if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString())) {
//                        isDeleteApi=true;
//                    }
//                } else {
//                    return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API删除任务信息失败！");
//                }
                if (isDeleteApi) {
                    List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskID(taskID);
                    for (FaceCameraEntity faceCameraEntity : listfaceCamera){
                        Long deleteID = faceCameraEntity.getIdFaceCamera();
                        if (faceCameraEntity.getStatus().equals(YNEnums.YES.code)){
                            faceCameraServiceImpl.status(deleteID,false);
                        }
                    }
                    // 更新本地数据库的状态为N
                    controlOne.setIsValid(TaskStatusEnum.STOP.code);
                    this.updateById(controlOne);
                } else {
                    return new CommonResult(taskID, SystemCode.DELETE_FAILED.code, "平台API删除任务信息失败");
                }}
            catch (Exception ex){
                if(log.isErrorEnabled()){
                    log.error("停止任务失败");
                }
                return new CommonResult(taskID, SystemCode.DELETE_FAILED.code, "停止任务失败");
            }
        }
        return new CommonResult(taskID, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
    }

    /**
     * 暂停任务  调用底层删除任务，本地库修改为暂停状态
     * @param taskID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult suspendControlByTaskID(String taskID) {

        ControlTask controlOne = this.getById(taskID);
        if (controlOne == null) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "参数异常，非法的任务ID！");
        } else {
            boolean isDeleteApi = false;
            try{
                //1. 调用平台API接口
//                Map<String, Object> resultMap = (Map<String, Object>) httpUtil.delete(link + ApiUrlEnum.TASK_POSTURL.getUrl() + "/" + controlOne.getTaskNo(), Map.class);
//                if (resultMap != null) {
//                    if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString())){
//                        isDeleteApi=true;
//                    }
//                } else {
//                    return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API删除任务信息失败！");
//                }
                System.out.println("开始暂停任务");
                String testUrl = "http://192.168.1.196:5001/stopTask/";
                System.out.println(taskID);
                System.out.println("开始暂停任务2");
                System.out.println(controlOne.getTaskNo());
                ReturnVO returnVO = (ReturnVO)httpUtil.get(testUrl+"?strtaskno="+controlOne.getTaskNo(),null, ReturnVO.class);
                System.out.println("输出暂停结果");
                System.out.println(returnVO);
                if(returnVO.getCode().equals(ErrEnum.OK.getCode())){
                    System.out.println("任务远程暂停成功");
                    isDeleteApi = true;
                }else {
                    System.out.println("远程任务暂停失败");
                }
                if (isDeleteApi) {
                    List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskID(taskID);
                    for (FaceCameraEntity faceCameraEntity : listfaceCamera){
                        Long deleteID = faceCameraEntity.getIdFaceCamera();
                        if (faceCameraEntity.getStatus().equals(YNEnums.YES.code)){
                            faceCameraServiceImpl.status(deleteID,false);
                        }
                    }
                    // 更新本地数据库的状态为暂停
                    controlOne.setIsValid(TaskStatusEnum.SUSPEND.code);
                    this.updateById(controlOne);
                } else {
                    return new CommonResult(taskID, SystemCode.DELETE_FAILED.code, "平台API删除任务信息失败");
                }}
            catch (Exception ex){
                return new CommonResult(taskID, SystemCode.DELETE_FAILED.code, ex.getMessage());
            }
        }
        return new CommonResult(taskID, SystemCode.HANDLER_SUCCESS.code, "暂停任务"+controlOne.getTaskName()+"成功");

    }

    /**
     *  恢复任务  调用底层新增任务，本地库修改为运行状态
     * @param taskID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult resumeControlByTaskID(String taskID) {
        //1. 构建任务对象
        ControlTask controlOne = this.getById(taskID);
        if (controlOne == null) {
            return new CommonResult(null, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "参数异常，非法的任务ID！");
        } else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id_control_task", taskID);
            //根据任务ID获取摄像头中间库
            List<ControlBayonetMid> listBayoneMid = controlBayonetMidService.list(queryWrapper);
            //获取摄像头
            if (UtilValidate.isEmpty(listBayoneMid)) {
                return new CommonResult(controlOne.getTaskName(), SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "恢复任务失败，该任务下没有查询到有效摄像头列表！");
            }
            List<FaceCameraEntity> listfaceCamera = controlTaskMapper.getCameraByTaskID(taskID);
            for (FaceCameraEntity faceCameraEntity : listfaceCamera){
                Long deleteID = faceCameraEntity.getIdFaceCamera();
                if (faceCameraEntity.getStatus().equals(YNEnums.NO.code)){
                    faceCameraServiceImpl.status(deleteID,true);
                }
            }
            //根据任务ID获取人像中间库
            List<ControlLibraryMid> listLibMid = controlLibraryMidService.list(queryWrapper);
            //获取人像中间库
            if(UtilValidate.isEmpty(listLibMid))
            {
                return new CommonResult(controlOne.getTaskName(), SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "恢复任务失败，该任务下没有查询到有效库列表！");
            }
            //摄像头列表ID
            List<String> listcamera = new ArrayList<>();
            for (ControlBayonetMid cbm : listBayoneMid) {
                listcamera.add(cbm.getIdFaceCamera().toString());
            }
            //获取人像中间库ID
            List<String> listfacelib= new ArrayList<>();
            for (ControlLibraryMid clb : listLibMid) {
                listfacelib.add(clb.getIdFactory().toString());
            }

            ControlTaskVO ctvo = new ControlTaskVO();
            ctvo.setName(controlOne.getTaskName());
            ctvo.setThreshold(controlOne.getControlThreshold());
            ctvo.setCameraId(listcamera);
            ctvo.setLibraryId(listfacelib);
            //恢复新建时把原来的NO重新发送过去
            ctvo.setTaskId(controlOne.getTaskNo());
            try {
                System.out.println("开始运行任务");
                String testUrl = "http://192.168.1.196:5001/startTask/";
                System.out.println(taskID);
                ReturnVO returnVO = (ReturnVO)httpUtil.get(testUrl+"?strtaskno="+controlOne.getTaskNo(),null, ReturnVO.class);
                System.out.println("输出运行结果");
                System.out.println(returnVO);
                if(returnVO.getCode().equals(ErrEnum.OK.getCode())){
                    System.out.println("任务远程恢复成功");
                    //3. 更新本地库任务的状态为RUN状态
                    String strTaskNo = controlOne.getTaskNo();
                    controlOne.setTaskNo(strTaskNo);
                    controlOne.setIsValid(TaskStatusEnum.RUN.code);
                    this.updateById(controlOne);
                }else {
                    System.out.println("远程任务恢复失败");
                }
                //2. 发送任务到API层
                // 调用平台API接口
//                String strTaskNo = "000000";
//                Map<String, Object> resultMap = (Map<String, Object>) httpUtil.post(link + ApiUrlEnum.TASK_POSTURL.getUrl(), ctvo, Map.class);
//                if (resultMap != null) {
//                    if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString())){
//                        Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
//                        if (data != null && data.get("taskId") != null) {
//                            strTaskNo = data.get("taskId").toString();
//                        } else {
//                            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！");
//                        }
//                    } else {
//                        return new CommonResult(resultMap, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！");
//                    }
//                } else {
//                    return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存任务信息失败！");
//                }

            }catch (Exception ex){
                if(log.isErrorEnabled()){
                    log.error("恢复任务异常{}：{}",controlOne.getTaskName(),ex.getMessage());
                }
            }
        }
        return new CommonResult(taskID, SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addtaskfaceFile(MultipartFile multipartFile) {
        FaceLibrary faceLibrary =new FaceLibrary();
        faceLibrary.setIsValid(YNEnums.YES.code);
        faceLibrary.setRemarks("任务图片上传临时库");
        Random r= new Random();
        faceLibrary.setFactoryName("任务图片上传库"+r.nextInt());
        faceLibrary.setFactoryType("-1");
        faceLibrary.setCreateTime(new Date());
        faceLibrary.setUpdateTime(new Date());
        faceLibrary.setCreateBy("SYSTASK");
        faceLibrary.setUpdateBy("SYSTASK");

        FaceLibrary faceLibrar = iFaceLibraryService.addLibrary(faceLibrary);
        if(UtilValidate.isEmpty(faceLibrar))
        {
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "生成特征库识别！");
        }
        //2.添加人脸信息特征
        Portrait portrait;
        try {
            portrait = iPortraitService.addPortraitPng(faceLibrar.getIdFactory().toString(), multipartFile);
        } catch (Exception e) {
            log.error("上传人像异常"+e.getMessage());
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, e.getMessage());
        }
        Map<String,Object> result=new HashMap<>();
        result.put("libid",faceLibrar.getIdFactory().toString());
        result.put("url",portrait.getBackgroundUrl());
        return new CommonResult(result,SystemCode.HANDLER_SUCCESS.code,"人像文件上传成功！");
    }

    @Override
    public CommonResult addtaskfaceFiles(String url) {
        FaceLibrary faceLibrary =new FaceLibrary();
        faceLibrary.setIsValid(YNEnums.YES.code);
        faceLibrary.setRemarks("任务图片上传临时库");
        Random r= new Random();
        faceLibrary.setFactoryName("任务图片上传库"+r.nextInt());
        faceLibrary.setFactoryType("-1");
        faceLibrary.setCreateTime(new Date());
        faceLibrary.setUpdateTime(new Date());
        faceLibrary.setCreateBy("SYSTASK");
        faceLibrary.setUpdateBy("SYSTASK");

        FaceLibrary faceLibrar = iFaceLibraryService.addLibrary(faceLibrary);
        if(UtilValidate.isEmpty(faceLibrar))
        {
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "生成特征库识别！");
        }
        //2.添加人脸信息特征
//        Portrait portrait;
//        try {
//            System.out.println(faceLibrar.getIdFactory().toString());
//            portrait = iPortraitService.addPortraitPngs(faceLibrar.getIdFactory().toString(), url);
//        } catch (Exception e) {
//            log.error("上传人像异常"+e.getMessage());
//            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, e.getMessage());
//        }
        Map<String,Object> result=new HashMap<>();
        result.put("libid",faceLibrar.getIdFactory().toString());
        result.put("url",url);
        return new CommonResult(result,SystemCode.HANDLER_SUCCESS.code,"人像文件上传成功！");
    }

    @Override
    public CommonResult addcomplevideoFile(MultipartFile multipartFile) {
        try {
            Pattern p = Pattern.compile(videoreg);
            boolean boo = p.matcher(multipartFile.getOriginalFilename()).find();
            if (!boo){
                return new CommonResult( null,SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code,  "上传文件必须是视频文件！");
            }
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String newname= UUID.randomUUID().toString().replace("-","").toLowerCase();
            JSONObject map = minioUtil.uploadFile(multipartFile.getInputStream(),newname, suffix);
            return new CommonResult(map, SystemCode.HANDLER_SUCCESS.code,SystemCode.HANDLER_SUCCESS.code.toString() );
        }catch (Exception ex){
            log.error("比对视频文件上传异常:{}",ex.getMessage());
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, ex.getMessage());
        }
    }

    @Override
    @Transactional
    public CommonResult addcomplevideoTask(VideoControlVo controlVO) {
        try {

            List<ControlLibraryMid> listbibray = new ArrayList<>();
            List<String> listbibraybyUse = new ArrayList<>();
            List<String> listlibs = controlVO.getLibIds();
            for (String libid : listlibs) {
                if (controlLibraryMidMapper.selectexistByLibID(libid, YNEnums.YES.code) > 0) {
                    ControlLibraryMid clm = new ControlLibraryMid();
                    clm.setIdFactory(Long.parseLong(libid.toString()));
                    clm.setIsValid(YNEnums.YES.code);
                    listbibray.add(clm);
                } else {
                    listbibraybyUse.add(libid);
                }
            }
            if (!UtilValidate.isEmpty(listbibraybyUse)) {
                return new CommonResult(listbibraybyUse, SystemCode.ILLEGAL_ARGUMENT_EXCEPTION.code, "该任务存在无效库！");
            }
            // 调用平台API接口
            ControlTaskVedioVO ctvo = new ControlTaskVedioVO();
            //任务名称
            String strTaskNo = "00000000";
            ctvo.setName("视频比对任务");
            ctvo.setThreshold(controlVO.getControlThreshold());
            ctvo.setUrl(controlVO.getVideourl());
            ctvo.setLibraryId(controlVO.getLibIds());


            Map<String,Object> resultMap = ( Map<String,Object>) httpUtil.post(link+ApiUrlEnum.TASK_VEDIO_POSTURL.getUrl(), ctvo,  Map.class);
            if(resultMap!=null){
                if(ErrEnum.OK.getCode().toString().equalsIgnoreCase(resultMap.get("code").toString()))
                {
                    Map<String,Object> data=  (Map<String,Object>) resultMap.get("data");
                    if(data!=null&&data.get("taskId")!=null){
                        strTaskNo=data.get("taskId").toString();
                    }else
                    {
                        return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存视频比对任务信息失败！未获取到任务ID");
                    }
                }else {
                    return new CommonResult(resultMap, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存视频比对任务信息失败！未获取OK表示");
                }
            }else {
                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "远程API保存视频比对任务信息失败！Map返回未空");
            }

            ControlTask controlTask = new ControlTask();
            controlTask.setTaskNo(strTaskNo);
            BeanUtils.copyProperties(controlVO, controlTask);
            controlTask.setIsValid(TaskStatusEnum.RUN.code);
            controlTask.setViedourl(controlVO.getVideourl());
            controlTask.setDisposalType("-1"); //视频对比
            controlTask.setControlType("0");
            controlTask.setControlObject("0");
            //保存任务
            if (this.save(controlTask)) {

                for (ControlLibraryMid clm : listbibray) {
                    //设置任务编号
                    clm.setIdControlTask(controlTask.getIdControlTask());
                }
                //批量 保存库ID列表
                controlLibraryMidService.saveBatch(listbibray);
                return new CommonResult(controlTask.getTaskNo(), SystemCode.HANDLER_SUCCESS.code, SystemCode.HANDLER_SUCCESS.des);
            } else {
                log.error("任务保存：{}", controlTask.getTaskNo());
                return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "保存任务信息失败！");
            }

        } catch (Exception ex) {
            log.error("保存任务异常：{}", ex.getMessage());
            return new CommonResult(null, SystemCode.INTERNAL_PROGRAM_ERROR.code, "保存任务信息失败！"+ex.getMessage());
        }

    }

    /**
     * 根据任务的区域码表字符串获取区域名称
     * @param regionstr
     * @return
     */
    @Override
    public String getCameraRegionStringByRegionstr(String regionstr) {

        Iterable<String> splits = Splitter.on(",").trimResults().omitEmptyStrings().split(regionstr);
        List<Long> listregion=new ArrayList<>();
        splits.forEach(region -> listregion.add(Long.parseLong(region)));
        if(listregion!=null&&listregion.size()>0){
            List<String> regionnames=controlTaskMapper.getCameraRegionByReginlist(listregion);
            return  Joiner.on("/").skipNulls().join(regionnames);
        }
        else{
            return "";
        }
    }

    /**
     * 根据摄像头列表获取区域的的字符串名称
     * @param cameraRegion
     * @return
     */
    public String getCameraRegionStringByCameraList(HashMap<String,Integer> cameraRegion){

        if(cameraRegion!=null&&cameraRegion.size()>0) {
            List<String> cameralist = new ArrayList<>();
            for (Map.Entry<String, Integer> mentry :
                    cameraRegion.entrySet()) {
                cameralist.add(mentry.getKey());
            }
            if (cameralist != null && cameralist.size() > 0 && cameralist.size() == 1) {
                return getCameraRegionStringByRegionstr(cameralist.get(0));
            } else {

                List<String[]> list = new ArrayList<>();
                for (String str : cameralist) {
                    String[] splitarray = str.split(",");
                    list.add(splitarray);
                }
                Collections.sort(list, new Comparator<String[]>() {
                    @Override
                    public int compare(String[] o1, String[] o2) {
                        if (o1.length > o2.length) {
                            return 1;
                        } else {
                            if (o1.length < o2.length) {
                                {
                                    return -1;
                                }
                            } else {
                                return 0;
                            }
                        }
                    }
                });

                StringBuilder sb = new StringBuilder();
                String[] str = list.get(0);
                int count = 0;
                for (String[] stra : list) {
                    if (stra.length == str.length) {
                        count++;
                    }
                }
                if (count >= 2) {
                    for (int i = 0; i < str.length - 1; i++) {
                        sb.append(str[i]+",");
                    }
                } else {
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]+",");
                    }
                }
                return getCameraRegionStringByRegionstr(sb.toString());
            }
        }
        return "";
    }


    @Override
    public String getLibRegionBytaskid(String taskID) {

        List<String> libsnames=controlTaskMapper.getLibRegionBytaskid(taskID);
        if(libsnames!=null){
            return  Joiner.on(",").skipNulls().join(libsnames);}
        else
        {return "";}

    }

    @Override
    public ControlTask getTaskInfoByCameraID(String Camera) {
        List<ControlTask> taskList=controlTaskMapper.getTaskInfoByCameraID(Camera);
        if(UtilValidate.isEmpty(taskList) || taskList.size()<=0)
        {
            return null;
        }
        return taskList.get(0);
    }
}
